/**
 * @file commom/utils/biz.js 辅助方法
 * @author zhanlong
 */

import u from 'underscore';
import {matchRoutes} from 'react-router-config';

import {title} from '../config';
import {isBrowser, getConfig} from './common';

/**
 * 根据 Component 的静态 dataRequired 属性，
 * 组合为一个 Promise 数组，数组参数为
 * - restful 路径解析出来的参数
 * - 调用时提供的参数
 * 混合而成的一个参数对象
 *
 * @param {Function<store.dispatch>} dispatch 事件发布方法
 * @param {string} path Component 对应的 react-router path，如 /:id/index
 * @param {Object<Router>} routes 路由对象
 * @param {Object=} params 调用 dispatch 方法时额外补充的参数
 * @return {Array<Promise>} promise 队列
 */

export function getDataPromises(dispatch, path, routes, params = {}) {
    const to = path.split('?')[0];
    const branch = matchRoutes(routes, to);
    const needs = branch.reduce((prev, {route, match}) => {
        const current = route.component;

        return Object.keys(current || {}).reduce((acc, key) => {
            const query = {...match.params, ...params};

            return current[key].hasOwnProperty('dataRequired')
                ? current[key].dataRequired.map(fetch => fetch(query)).concat(acc)
                : acc;
        }, prev);
    }, []);

    return needs.map(need => dispatch(need));
}

export function getHTMLTitle(path, store) {
    // TODO: any hijacks ?

    return title;
}

export function resetAPPHeader(title) {
    if (isBrowser()) {
        window.document.title = title;
    }
}

export function getRouteConfigFromPath(routes, pathname) {
    let routeConfig;

    const branches = matchRoutes(routes, pathname);

    branches.some(({route, match}, index) => {
        if (match.isExact) {
            routeConfig = route;
            return true;
        }
    });

    return routeConfig;
}

export function getSidebarConfig(pathname) {
    // import将导致utils在Component之外不可用
    /* eslint-disable */
    const routes = require('../routes').default;
    const {SIDEBAR_CONFIG} = require('../constants');
    /* eslint-enable */

    let {defaultKey, navs} = SIDEBAR_CONFIG;
    let routeConfig = getRouteConfigFromPath(routes, pathname);
    let config;

    if (routeConfig) {
        let path = routeConfig.path || (routeConfig.routes[0].path);

        // 无法通过url判等直接从导航配置中获取到对应路径的配置
        // 则通过anchors获取，若还无法获取到则取默认配置
        config = getConfig('url', path, navs)
            || getConfig('anchors', path, navs)
            || getConfig('key', defaultKey, navs);
    }
    else {
        config = getConfig('key', defaultKey, navs);
    }

    return config;
}

export function createAction(actionType, payload) {
    return function (query) {
        return async dispatch => {
            try {
                const result = await payload(query);

                return dispatch({
                    type: actionType,
                    data: result
                });
            }
            catch (err) {
                return Promise.reject(err);
            }
        };
    };
}
